var widget = {
    alert: function (msg) {
        console.info(msg);
    },
    error: function (msg) {
        try{
            console.error(msg);
        } catch (e) {
            console.info(e);
        }
    },
    info: function (msg) {
        console.info(msg);
    }
};
var Error = H5Client.Error;
// 自定义错误消息，可覆盖
Error.GENERIC_OPERATION = {
    code: 498,
    // 自定义未使用的错误号
    name: 'GENERIC_OPERATION',
    // 异常名称等于错误属性名称
    message: '操作失败，可能分机已被登录，或者分机号码未被注册（ONE-X或实体话机）',
    // 自定义错误消息
    type: 'user' // 自定义错误类型
};
Error.INVALID_STATE_ERR = {
    code: 407,
    name: "INVALID_STATE_ERR",
    message: "状态错误",
    type: "client"
};

// 获得会话对象
var Session = H5Client.Session;
var session = new Session();

// 获得事件对象
var event = session.event;
// 获得分机对象
var Station = H5Client.Station;
var station = new Station(session);
var agent = station.agent;

var Group = H5Client.Group;
var group = new Group(session);

var Agent = H5Client.Agent;
var Call = H5Client.Call;
var Query = new H5Client.Query(session);
//存放小休原因码的名称
var ReasonCodeName = new Array();
//存放小休原因码标志
var ReasonCodeSign = "";
//小休原因码标志位
var hadFinishedReasonCode = false;

var onlineType = "";

// 退出或刷新时关闭session
window.onbeforeunload = function () {
    if (Session.ALIVE === session.state) {
        //            session.end();
    }
}

/**
 * 坐席状态发生变化
 */
function checkState()
{
    //        logger.log("checkState");
    if (session.state === Session.DEAD || station.state === Station.PENDING)
    {
        if (agent.mode !== Agent.PENDING && agent.mode !== Agent.LOGOUT)
        {
            return;
        }
    }
    switch (agent.mode)
    {
    case Agent.LOGIN:
        widget.info('登录成功');
        //设置电话为第三方拨打状态
        //top.myEtalkEvent.dialBtn.setValue("phoneDial");
        break;
        case Agent.READY://就绪
            widget.info('就绪');
            break;
        case Agent.NOT_READY://未就绪
            widget.info("未就绪");
            break;
        case Agent.WORK_NOT_READY://后处理
            break;
        case Agent.LOGOUT:
        case Agent.PENDING://未登录
            // 避免Session在退出工号时被意外结束掉
            if (station.state === Station.MONITORED)
            {
                session.end().then(function (){
                });
            }
            stationInfo = '';
            break;
        default:
            break;
    }
}

// 监听坐席状态改变事件
event.on('user.AgentStateChange', function (e) {
    console.info("user.AgentStateChange:", e);
    if (e.srcDeviceId !== station.deviceId) return;
    checkState();
    top.softphone.agentStateChangeBtnUpdate(e);
});

// 监听组状态改变事件
event.on('user.Snapshot', function (e) {
    console.info("user.Snapshot:", e);
    if (e.srcDeviceId !== group.deviceId)
    {
        return;
    }
    widget.alert("group.callsInQueue:" + group.callsInQueue);
});

event.on('user.Disconnected', function () {
    widget.alert('连接断开!');
    top.softphone.showErrorInfo("连接断开", "坐席与CTI连接断开，请尝试重连！", false);
});

event.on('user.Connecting', function (e) {
    console.info("user.Connecting:", e);
    widget.alert('正在重连(' + e.reconnectAttempts + ')...');
});

event.on('user.Reconnected', function (e) {
    console.info("user.Reconnected:", e);
    widget.alert('重连成功，正在恢复数据...');
});

event.on('user.Recovered', function (e) {
    console.info("user.Recovered:", e);
    if (e.length)
    {
        widget.alert('恢复出现异常');
    }
    else
    {
        widget.alert('恢复成功');
    }
});

//转接和会议会产生新会话，用此对象保存原始sessionId
let sessionEntry = {};
//会话类型'n'新会话，'t'转接会话，'c'会议会话
let sessionType = 'n';
//当前会话中的sessionId
let ivrSessionId = "";
//振铃事件
event.on('user.Delivered', function (e)
{
    console.info("user.Delivered:", e);
    if (e.srcDeviceId !== station.deviceId)
    {
        return;
    }
    let call = station.calls.get(e.callId);
    if (!call)
    {
        return;
    }
    top.softphone.answerBtnStatusUpdate(true);
    top.softphone.agentStatusTimeUpdate("振铃中");
    console.info("user.Delivered call:", call);
    console.info("user.Delivered station:", station);
    //直接呼叫分机
    if (( typeof e.userData === 'undefined' || 
          e.userData === null || 
          typeof e.userData.map === 'undefined' || 
          e.userData.map === null || 
          typeof e.userData.map.uui === 'undefined' || 
          e.userData.map.uui === null
        ) &&
        e.alertingDevice === station.deviceId && 
        ( e.calledDevice === station.deviceId || 
          e.calledDevice === station.agent.agentId
        )
       )
    {
        console.info("user.Delivered call: 直接呼叫分机");
      
    }
    //直接呼叫技能组呼入
    else if ((typeof e.userData === 'undefined' || 
              e.userData === null || 
              typeof e.userData.map === 'undefined' || 
              e.userData.map === null || 
              typeof e.userData.map.uui === 'undefined' || 
              e.userData.map.uui === null 
             ) &&
             e.alertingDevice === station.deviceId && 
             e.calledDevice !== station.deviceId && 
             e.calledDevice !== station.agent.agentId && 
             typeof e.split !== 'undefined' && 
             e.split !== null && 
             e.split !== ""
            )
    {
        console.info("user.Delivered call: 直接呼叫技能组呼入");
        let data = {};
        let ucid = e.contactId;
        let sessionId = ucid + station.agent.agentId + top.DateUtil.now("hhmmss");
        top.softphone.currentUcid = ucid;
        top.softphone.currentContactId = ucid;
        data["sessionId"] = sessionId;
        data["ucid"] = ucid;
        data["contactId"] = e.contactId;
        data["originalContactId"] = e.originalContactId;
        data["callId"] = e.callId;
        data["callGroup"] = e.split;
        data["autoAnswer"] = false;
        data['isTransferIvr'] = false;
        data['isconnected'] = false;
        data['isHangup'] = false;
        for(let indNo in top.softphone.agentgroupList)
        {
            let groupObj = top.softphone.agentgroupList[indNo];
            if(groupObj["groupNo"] === e.split)
            {
                data["autoAnswer"] = groupObj["groupAutoAnswer"];
            }
        }
        data["callGroupVdn"] = e.calledDevice;
        data["timestamp"] = e.timestamp;
        data["ani"] = call.ani;
        data["dnis"] = call.dnis;
        data["queue"] = call.queue;
        data["direction"] = call.direction;
        data["sessionType"] = "n";
        data['whoDropCall'] = "";
        data["custData"] = {};
        data["custData"]["LANGUAGE"] = "0";
        data["custData"]["MSG"] = "";
        data["custData"]["EXTIDX"] = "2";
        data["custData"]["DNIS"] = call.dnis;
        data["custData"]["ANIS"] = call.ani;
        data["custData"]["BNKNBR"] = top.softphone.tenantId;
        data["custData"]["BUSITYPE"] = "";
        data["custData"]["TRANSFBUSTYPE"] = "";
        data["custData"]["MENUID"] = "";
        data["custData"]["TRNDRI"] = "0";
        data["custData"]["TRNCNT"] = "1";
        data["custData"]["ACTYPE"] = "9";
        data["custData"]["MSGID"] = "";
        data["custData"]["CARD"] = "";
        data["custData"]["IDTYPE"] = "";
        data["custData"]["IDNO"] = "";
        data["custData"]["AUTH"] = "";
        data["custData"]["CALLSTATUS"] = "0";
        data["custData"]["USERINFO"] = "null|8|null|null";
        data["custData"]["NAME"] = "";
        data["custData"]["ENNAME"] = "";
        data["custData"]["HOMETELNO"] = "";
        data["custData"]["MOBILEPHONE"] = "";
        data["custData"]["CUSTNO"] = "";
        data["custData"]["OPERATETRAJECT"] = "";
        console.info("user.Delivered custData:", data);
        top.softphone.sessionMap[sessionId] = data;
        top.softphone.ucidMap[ucid] = sessionId;
        top.softphone.ucidMap[e.contactId] = sessionId;
        //振铃弹屏
        top.softphone.openNewSession(data);
        if(data.autoAnswer) //自动应答
        {
            console.info('坐席延迟2秒自动应答，防止无振铃声就接起！');
            setTimeout(top.softphone.answerBtnClick(), 2000);
        }
        top.softphone.insertCallHistory(top.softphone.sessionMap[sessionId]);//插入呼叫历史
    }
    //外呼振铃-生产外线呼出不会产生振铃事件
    else if ((typeof e.userData === 'undefined' || 
              e.userData === null || 
              typeof e.userData.map === 'undefined' || 
              e.userData.map === null || 
              typeof e.userData.map.uui === 'undefined' || 
              e.userData.map.uui === null 
             ) &&
             e.alertingDevice !== station.deviceId && 
             e.alertingDevice !== station.agent.agentId && 
             e.callingDevice === station.deviceId && 
             e.calledDevice !== station.deviceId && 
             e.calledDevice !== station.agent.agentId && 
             (typeof e.split === 'undefined' || 
              e.split === null || 
              e.split === ""
             )
            )
    {
        console.info("user.Delivered call: 生产外线呼出不会产生振铃事件");
        return; 
    }
    //自助语音IVR首次呼入
    else if (typeof e.userData !== 'undefined' && 
             e.userData !== null && 
             typeof e.userData.map !== 'undefined' && 
             e.userData.map !== null && 
             typeof e.userData.map.uui !== 'undefined' && 
             e.userData.map.uui !== null &&
             (typeof e.userData.map.type === 'undefined' || 
              e.userData.map.type === null || 
              e.userData.map.type === ""
             ) && 
             e.alertingDevice === station.deviceId && 
             e.calledDevice !== station.agent.agentId
            )
    {
        console.info("user.Delivered call: 自助语音IVR首次呼入");
        let data = {};
        let ucid = e.userData.map.uui;
        let sessionId = ucid + station.agent.agentId + top.DateUtil.now("hhmmss");
        top.softphone.currentUcid = ucid;
        top.softphone.currentContactId = e.contactId;
        data["sessionId"] = sessionId;
        data["ucid"] = ucid;
        data["contactId"] = e.contactId;
        data["originalContactId"] = e.originalContactId;
        data["callId"] = e.callId;
        data["callGroup"] = e.split;
        data["autoAnswer"] = false;
        data['isTransferIvr'] = false;
        data['isconnected'] = false;
        data['isHangup'] = false;
        for(let indNo in top.softphone.agentgroupList)
        {
            let groupObj = top.softphone.agentgroupList[indNo];
            if(groupObj["groupNo"] === e.split)
            {
                data["autoAnswer"] = groupObj["groupAutoAnswer"];
            }
        }
        data["callGroupVdn"] = e.calledDevice;
        data["timestamp"] = e.timestamp;
        data["ani"] = call.ani;
        data["dnis"] = call.dnis;
        data["queue"] = call.queue;
        data["direction"] = call.direction;
        data["sessionType"] = "n";
        data['whoDropCall'] = "";
        data["custData"] = {};
        // 获取随路数据
        let IvrJsonData = top.softphone.getSoftPhoneIVRData(ucid);
        data["custData"]["CUSTNO"] = "";
        data["custData"]["OPERATETRAJECT"] = "";
        if(IvrJsonData !== null)
        {
             data["custData"]["LANGUAGE"] = IvrJsonData.LANGUAGE;
             data["custData"]["MSG"] = IvrJsonData.MSG;
             data["custData"]["EXTIDX"] = IvrJsonData.EXTIDX;
             data["custData"]["DNIS"] = IvrJsonData.DNIS;
             data["custData"]["ANIS"] = IvrJsonData.ANIS;
             data["custData"]["BNKNBR"] = IvrJsonData.BNKNBR;
             data["custData"]["BUSITYPE"] = IvrJsonData.BUSITYPE;
             data["custData"]["TRANSFBUSTYPE"] = IvrJsonData.TRANSFBUSTYPE;
             data["custData"]["MENUID"] = IvrJsonData.MENUID;
             data["custData"]["TRNDRI"] = IvrJsonData.TRNDRI;
             data["custData"]["TRNCNT"] = IvrJsonData.TRNCNT;
             data["custData"]["ACTYPE"] = IvrJsonData.ACTYPE;
             data["custData"]["MSGID"] = IvrJsonData.MSGID;
             data["custData"]["CARD"] = IvrJsonData.CARD;
             data["custData"]["IDTYPE"] = IvrJsonData.IDTYPE;
             data["custData"]["IDNO"] = IvrJsonData.IDNO;
             data["custData"]["AUTH"] = IvrJsonData.AUTH;
             data["custData"]["CALLSTATUS"] = IvrJsonData.CALLSTATUS;
             data["custData"]["USERINFO"] = IvrJsonData.USERINFO;
             if (typeof IvrJsonData.OPERATETRAJECT !== 'undefined' && IvrJsonData.OPERATETRAJECT != null)
             {
                 data["custData"]["OPERATETRAJECT"] = IvrJsonData.OPERATETRAJECT;
             }
        }
        else
        {
             data["custData"]["LANGUAGE"] = "0";
             data["custData"]["MSG"] = "";
             data["custData"]["EXTIDX"] = "2";
             data["custData"]["DNIS"] = call.dnis;
             data["custData"]["ANIS"] = call.ani;
             data["custData"]["BNKNBR"] = top.softphone.tenantId;
             data["custData"]["BUSITYPE"] = "";
             data["custData"]["TRANSFBUSTYPE"] = "";
             data["custData"]["MENUID"] = "";
             data["custData"]["TRNDRI"] = "0";
             data["custData"]["TRNCNT"] = "1";
             data["custData"]["ACTYPE"] = "9";
             data["custData"]["MSGID"] = "";
             data["custData"]["CARD"] = "";
             data["custData"]["IDTYPE"] = "";
             data["custData"]["IDNO"] = "";
             data["custData"]["AUTH"] = "";
             data["custData"]["CALLSTATUS"] = "0";
             data["custData"]["USERINFO"] = "null|8|null|null";
        }
        data["custData"]["NAME"] = "";
        data["custData"]["ENNAME"] = "";
        data["custData"]["HOMETELNO"] = "";
        data["custData"]["MOBILEPHONE"] = "";
        console.info("user.Delivered custData:", data);
        top.softphone.sessionMap[sessionId] = data;
        top.softphone.ucidMap[ucid] = sessionId;
        top.softphone.ucidMap[e.contactId] = sessionId;
        //振铃弹屏
        top.softphone.openNewSession(data);
        if(data.autoAnswer) //自动应答
        {
            console.info('坐席延迟2秒自动应答，防止无振铃声就接起！');
            setTimeout(top.softphone.answerBtnClick(), 2000);
        }
        top.softphone.insertCallHistory(top.softphone.sessionMap[sessionId]);//插入呼叫历史 
    }
    //自助语音IVR转回人工
    else if (typeof e.userData !== 'undefined' && 
             e.userData !== null && 
             typeof e.userData.map !== 'undefined' && 
             e.userData.map !== null && 
             typeof e.userData.map.uui !== 'undefined' && 
             e.userData.map.uui !== null &&
             (typeof e.userData.map.type === 'undefined' || 
              e.userData.map.type === null || 
              e.userData.map.type === ""
             ) && 
             e.alertingDevice === station.deviceId && 
             e.calledDevice === station.agent.agentId
            )
    {
        console.info("user.Delivered call: 自助语音IVR转回人工");
        let ucid = e.userData.map.uui;
        let sessionId = top.softphone.ucidMap[ucid];
        top.softphone.currentUcid = ucid;
        top.softphone.currentContactId = top.softphone.sessionMap[sessionId].contactId;
        // 是否在IVR流程：1-是，0-否
        top.softphone.sessionMap[sessionId]['isTransferIvr'] = false;
        // 获取随路数据
        let IvrJsonData = top.softphone.getSoftPhoneIVRData(ucid);
        if(IvrJsonData !== null)
        {
            IvrJsonData['ucid'] = ucid;
            IvrJsonData['sessionId'] = sessionId;
            //更新转接IVR流程结果
            top.softphone.ivrReturnToAgent(IvrJsonData);
        }
        if(top.softphone.sessionMap[sessionId].autoAnswer) //自动应答
        {
            console.info('坐席延迟2秒自动应答，防止无振铃声就接起！');
            setTimeout(top.softphone.answerBtnClick(), 2000);
        }
        //激活会话
        top.softphone.activeSession(sessionId);
        console.info("user.Delivered IVR data:", top.softphone.sessionMap[sessionId]);
        top.softphone.updateCallHistory("ivrring", top.softphone.sessionMap[sessionId]);//更新呼叫历史
    }
    //其他坐席转接过来首次振铃
    else if (typeof e.userData !== 'undefined' && 
             e.userData !== null && 
             typeof e.userData.map !== 'undefined' && 
             e.userData.map !== null && 
             typeof e.userData.map.uui !== 'undefined' && 
             e.userData.map.uui !== null &&
             typeof e.userData.map.type !== 'undefined' && 
             e.userData.map.type !== null && 
             e.userData.map.type === "t" && 
             e.alertingDevice === station.deviceId && 
             e.calledDevice === station.agent.agentId
            )
    {
        console.info("user.Delivered call: 其他坐席转接过来首次振铃");
        let data = {};
        let ucid = e.userData.map.uui;
        let sessionId = ucid + station.agent.agentId + top.DateUtil.now("hhmmss");
        let dataArr = (e.userData.map.d).split("|");
        top.softphone.currentUcid = ucid;
        top.softphone.currentContactId = e.contactId;
        data["sessionId"] = sessionId;
        data["ucid"] = ucid;
        data["contactId"] = e.contactId;
        data["originalContactId"] = e.originalContactId;
        data["callId"] = e.callId;
        data["callGroup"] = dataArr[2];
        data["autoAnswer"] = false;
        data['isTransferIvr'] = false;
        data['isconnected'] = false;
        data['isHangup'] = false;
        for(let indNo in top.softphone.agentgroupList)
        {
            let groupObj = top.softphone.agentgroupList[indNo];
            if(groupObj["groupNo"] === e.split)
            {
                data["autoAnswer"] = groupObj["groupAutoAnswer"];
            }
        }
        data["callGroupVdn"] = e.calledDevice;
        data["timestamp"] = e.timestamp;
        data["ani"] = dataArr[0];
        data["dnis"] = dataArr[1];
        data["queue"] = call.queue;
        data["direction"] = dataArr[3];
        data["sessionType"] = "t";
        data['whoDropCall'] = "";
        data["custData"] = {};
        // 获取随路数据
        let IvrJsonData = top.softphone.getSoftPhoneIVRData(ucid);
        data["custData"]["CUSTNO"] = "";
        data["custData"]["OPERATETRAJECT"] = "";
        if(IvrJsonData !== null)
        {
             data["custData"]["LANGUAGE"] = IvrJsonData.LANGUAGE;
             data["custData"]["MSG"] = IvrJsonData.MSG;
             data["custData"]["EXTIDX"] = IvrJsonData.EXTIDX;
             data["custData"]["DNIS"] = IvrJsonData.DNIS;
             data["custData"]["ANIS"] = IvrJsonData.ANIS;
             data["custData"]["BNKNBR"] = IvrJsonData.BNKNBR;
             data["custData"]["BUSITYPE"] = IvrJsonData.BUSITYPE;
             data["custData"]["TRANSFBUSTYPE"] = IvrJsonData.TRANSFBUSTYPE;
             data["custData"]["MENUID"] = IvrJsonData.MENUID;
             data["custData"]["TRNDRI"] = IvrJsonData.TRNDRI;
             data["custData"]["TRNCNT"] = IvrJsonData.TRNCNT;
             data["custData"]["ACTYPE"] = IvrJsonData.ACTYPE;
             data["custData"]["MSGID"] = IvrJsonData.MSGID;
             data["custData"]["CARD"] = IvrJsonData.CARD;
             data["custData"]["IDTYPE"] = IvrJsonData.IDTYPE;
             data["custData"]["IDNO"] = IvrJsonData.IDNO;
             data["custData"]["AUTH"] = IvrJsonData.AUTH;
             data["custData"]["CALLSTATUS"] = IvrJsonData.CALLSTATUS;
             data["custData"]["USERINFO"] = IvrJsonData.USERINFO;
             if (typeof IvrJsonData.OPERATETRAJECT !== 'undefined' && IvrJsonData.OPERATETRAJECT != null)
             {
                 data["custData"]["OPERATETRAJECT"] = IvrJsonData.OPERATETRAJECT;
             }
        }
        else
        {
             data["custData"]["LANGUAGE"] = "0";
             data["custData"]["MSG"] = "";
             data["custData"]["EXTIDX"] = "2";
             data["custData"]["DNIS"] = call.dnis;
             data["custData"]["ANIS"] = call.ani;
             data["custData"]["BNKNBR"] = top.softphone.tenantId;
             data["custData"]["BUSITYPE"] = "";
             data["custData"]["TRANSFBUSTYPE"] = "";
             data["custData"]["MENUID"] = "";
             data["custData"]["TRNDRI"] = "0";
             data["custData"]["TRNCNT"] = "1";
             data["custData"]["ACTYPE"] = "9";
             data["custData"]["MSGID"] = "";
             data["custData"]["CARD"] = "";
             data["custData"]["IDTYPE"] = "";
             data["custData"]["IDNO"] = "";
             data["custData"]["AUTH"] = "";
             data["custData"]["CALLSTATUS"] = "0";
             data["custData"]["USERINFO"] = "null|8|null|null";
        }
        data["custData"]["NAME"] = "";
        data["custData"]["ENNAME"] = "";
        data["custData"]["HOMETELNO"] = "";
        data["custData"]["MOBILEPHONE"] = "";
        console.info("user.Delivered custData:", data);
        top.softphone.sessionMap[sessionId] = data;
        top.softphone.ucidMap[ucid] = sessionId;
        top.softphone.ucidMap[e.contactId] = sessionId;
        //振铃弹屏
        top.softphone.openNewSession(data);
        if(data.autoAnswer) //自动应答
        {
            console.info('坐席延迟2秒自动应答，防止无振铃声就接起！');
            setTimeout(top.softphone.answerBtnClick(), 2000);
        }
        top.softphone.insertCallHistory(top.softphone.sessionMap[sessionId]);//插入呼叫历史
    }
    //其他坐席通过技能组转接过来首次振铃
    else if (typeof e.userData !== 'undefined' && 
             e.userData !== null && 
             typeof e.userData.map !== 'undefined' && 
             e.userData.map !== null && 
             typeof e.userData.map.uui !== 'undefined' && 
             e.userData.map.uui !== null &&
             typeof e.userData.map.type !== 'undefined' && 
             e.userData.map.type !== null && 
             e.userData.map.type === "g" && 
             e.alertingDevice === station.deviceId && 
             e.calledDevice !== station.agent.agentId
            )
    {
        console.info("user.Delivered call: 其他坐席通过技能组转接过来首次振铃");
        let data = {};
        let ucid = e.userData.map.uui;
        let sessionId = ucid + station.agent.agentId + top.DateUtil.now("hhmmss");
        let dataArr = (e.userData.map.d).split("|");
        top.softphone.currentUcid = ucid;
        top.softphone.currentContactId = e.contactId;
        data["sessionId"] = sessionId;
        data["ucid"] = ucid;
        data["contactId"] = e.contactId;
        data["originalContactId"] = e.originalContactId;
        data["callId"] = e.callId;
        data["callGroup"] = e.split;
        data["autoAnswer"] = false;
        data['isTransferIvr'] = false;
        data['isconnected'] = false;
        data['isHangup'] = false;
        for(let indNo in top.softphone.agentgroupList)
        {
            let groupObj = top.softphone.agentgroupList[indNo];
            if(groupObj["groupNo"] === e.split)
            {
                data["autoAnswer"] = groupObj["groupAutoAnswer"];
            }
        }
        data["callGroupVdn"] = e.calledDevice;
        data["timestamp"] = e.timestamp;
        data["ani"] = dataArr[0];
        data["dnis"] = dataArr[1];
        data["queue"] = call.queue;
        data["direction"] = dataArr[3];
        data["sessionType"] = "g";
        data['whoDropCall'] = "";
        data["custData"] = {};
        // 获取随路数据
        let IvrJsonData = top.softphone.getSoftPhoneIVRData(ucid);
        data["custData"]["CUSTNO"] = "";
        data["custData"]["OPERATETRAJECT"] = "";
        if(IvrJsonData !== null)
        {
             data["custData"]["LANGUAGE"] = IvrJsonData.LANGUAGE;
             data["custData"]["MSG"] = IvrJsonData.MSG;
             data["custData"]["EXTIDX"] = IvrJsonData.EXTIDX;
             data["custData"]["DNIS"] = IvrJsonData.DNIS;
             data["custData"]["ANIS"] = IvrJsonData.ANIS;
             data["custData"]["BNKNBR"] = IvrJsonData.BNKNBR;
             data["custData"]["BUSITYPE"] = IvrJsonData.BUSITYPE;
             data["custData"]["TRANSFBUSTYPE"] = IvrJsonData.TRANSFBUSTYPE;
             data["custData"]["MENUID"] = IvrJsonData.MENUID;
             data["custData"]["TRNDRI"] = IvrJsonData.TRNDRI;
             data["custData"]["TRNCNT"] = IvrJsonData.TRNCNT;
             data["custData"]["ACTYPE"] = IvrJsonData.ACTYPE;
             data["custData"]["MSGID"] = IvrJsonData.MSGID;
             data["custData"]["CARD"] = IvrJsonData.CARD;
             data["custData"]["IDTYPE"] = IvrJsonData.IDTYPE;
             data["custData"]["IDNO"] = IvrJsonData.IDNO;
             data["custData"]["AUTH"] = IvrJsonData.AUTH;
             data["custData"]["CALLSTATUS"] = IvrJsonData.CALLSTATUS;
             data["custData"]["USERINFO"] = IvrJsonData.USERINFO;
             if (typeof IvrJsonData.OPERATETRAJECT !== 'undefined' && IvrJsonData.OPERATETRAJECT != null)
             {
                 data["custData"]["OPERATETRAJECT"] = IvrJsonData.OPERATETRAJECT;
             }
        }
        else
        {
             data["custData"]["LANGUAGE"] = "0";
             data["custData"]["MSG"] = "";
             data["custData"]["EXTIDX"] = "2";
             data["custData"]["DNIS"] = call.dnis;
             data["custData"]["ANIS"] = call.ani;
             data["custData"]["BNKNBR"] = top.softphone.tenantId;
             data["custData"]["BUSITYPE"] = "";
             data["custData"]["TRANSFBUSTYPE"] = "";
             data["custData"]["MENUID"] = "";
             data["custData"]["TRNDRI"] = "0";
             data["custData"]["TRNCNT"] = "1";
             data["custData"]["ACTYPE"] = "9";
             data["custData"]["MSGID"] = "";
             data["custData"]["CARD"] = "";
             data["custData"]["IDTYPE"] = "";
             data["custData"]["IDNO"] = "";
             data["custData"]["AUTH"] = "";
             data["custData"]["CALLSTATUS"] = "0";
             data["custData"]["USERINFO"] = "null|8|null|null";
        }
        data["custData"]["NAME"] = "";
        data["custData"]["ENNAME"] = "";
        data["custData"]["HOMETELNO"] = "";
        data["custData"]["MOBILEPHONE"] = "";
        console.info("user.Delivered custData:", data);
        top.softphone.sessionMap[sessionId] = data;
        top.softphone.ucidMap[ucid] = sessionId;
        top.softphone.ucidMap[e.contactId] = sessionId;
        //振铃弹屏
        top.softphone.openNewSession(data);
        if(data.autoAnswer) //自动应答
        {
            console.info('坐席延迟2秒自动应答，防止无振铃声就接起！');
            setTimeout(top.softphone.answerBtnClick(), 2000);
        }
        top.softphone.insertCallHistory(top.softphone.sessionMap[sessionId]);//插入呼叫历史
         
    }
    //其他坐席邀请会议首次振铃
    else if (typeof e.userData !== 'undefined' && 
             e.userData !== null && 
             typeof e.userData.map !== 'undefined' && 
             e.userData.map !== null && 
             typeof e.userData.map.uui !== 'undefined' && 
             e.userData.map.uui !== null &&
             typeof e.userData.map.type !== 'undefined' && 
             e.userData.map.type !== null && 
             e.userData.map.type === "c" && 
             e.alertingDevice === station.deviceId && 
             e.calledDevice === station.agent.agentId
            )
    {
        console.info("user.Delivered call: 其他坐席邀请会议首次振铃");
        let data = {};
        let ucid = e.userData.map.uui;
        let sessionId = ucid + station.agent.agentId + top.DateUtil.now("hhmmss");
        let dataArr = (e.userData.map.d).split("|");
        top.softphone.currentUcid = ucid;
        top.softphone.currentContactId = e.contactId;
        data["sessionId"] = sessionId;
        data["ucid"] = ucid;
        data["contactId"] = e.contactId;
        data["originalContactId"] = e.originalContactId;
        data["callId"] = e.callId;
        data["callGroup"] = dataArr[2];
        data["autoAnswer"] = false;
        data['isTransferIvr'] = false;
        data['isconnected'] = false;
        data['isHangup'] = false;
        for(let indNo in top.softphone.agentgroupList)
        {
            let groupObj = top.softphone.agentgroupList[indNo];
            if(groupObj["groupNo"] === e.split)
            {
                data["autoAnswer"] = groupObj["groupAutoAnswer"];
            }
        }
        data["callGroupVdn"] = e.calledDevice;
        data["timestamp"] = e.timestamp;
        data["ani"] = dataArr[0];
        data["dnis"] = dataArr[1];
        data["queue"] = call.queue;
        data["direction"] = dataArr[3];
        data["sessionType"] = "c";
        data['whoDropCall'] = "";
        data["custData"] = {};
        // 获取随路数据
        let IvrJsonData = top.softphone.getSoftPhoneIVRData(ucid);
        data["custData"]["CUSTNO"] = "";
        data["custData"]["OPERATETRAJECT"] = "";
        if(IvrJsonData !== null)
        {
             data["custData"]["LANGUAGE"] = IvrJsonData.LANGUAGE;
             data["custData"]["MSG"] = IvrJsonData.MSG;
             data["custData"]["EXTIDX"] = IvrJsonData.EXTIDX;
             data["custData"]["DNIS"] = IvrJsonData.DNIS;
             data["custData"]["ANIS"] = IvrJsonData.ANIS;
             data["custData"]["BNKNBR"] = IvrJsonData.BNKNBR;
             data["custData"]["BUSITYPE"] = IvrJsonData.BUSITYPE;
             data["custData"]["TRANSFBUSTYPE"] = IvrJsonData.TRANSFBUSTYPE;
             data["custData"]["MENUID"] = IvrJsonData.MENUID;
             data["custData"]["TRNDRI"] = IvrJsonData.TRNDRI;
             data["custData"]["TRNCNT"] = IvrJsonData.TRNCNT;
             data["custData"]["ACTYPE"] = IvrJsonData.ACTYPE;
             data["custData"]["MSGID"] = IvrJsonData.MSGID;
             data["custData"]["CARD"] = IvrJsonData.CARD;
             data["custData"]["IDTYPE"] = IvrJsonData.IDTYPE;
             data["custData"]["IDNO"] = IvrJsonData.IDNO;
             data["custData"]["AUTH"] = IvrJsonData.AUTH;
             data["custData"]["CALLSTATUS"] = IvrJsonData.CALLSTATUS;
             data["custData"]["USERINFO"] = IvrJsonData.USERINFO;
             if (typeof IvrJsonData.OPERATETRAJECT !== 'undefined' && IvrJsonData.OPERATETRAJECT != null)
             {
                 data["custData"]["OPERATETRAJECT"] = IvrJsonData.OPERATETRAJECT;
             }
        }
        else
        {
             data["custData"]["LANGUAGE"] = "0";
             data["custData"]["MSG"] = "";
             data["custData"]["EXTIDX"] = "2";
             data["custData"]["DNIS"] = call.dnis;
             data["custData"]["ANIS"] = call.ani;
             data["custData"]["BNKNBR"] = top.softphone.tenantId;
             data["custData"]["BUSITYPE"] = "";
             data["custData"]["TRANSFBUSTYPE"] = "";
             data["custData"]["MENUID"] = "";
             data["custData"]["TRNDRI"] = "0";
             data["custData"]["TRNCNT"] = "1";
             data["custData"]["ACTYPE"] = "9";
             data["custData"]["MSGID"] = "";
             data["custData"]["CARD"] = "";
             data["custData"]["IDTYPE"] = "";
             data["custData"]["IDNO"] = "";
             data["custData"]["AUTH"] = "";
             data["custData"]["CALLSTATUS"] = "0";
             data["custData"]["USERINFO"] = "null|8|null|null";
        }
        data["custData"]["NAME"] = "";
        data["custData"]["ENNAME"] = "";
        data["custData"]["HOMETELNO"] = "";
        data["custData"]["MOBILEPHONE"] = "";
        console.info("user.Delivered custData:", data);
        top.softphone.sessionMap[sessionId] = data;
        top.softphone.ucidMap[ucid] = sessionId;
        top.softphone.ucidMap[e.contactId] = sessionId;
        //振铃弹屏
        top.softphone.openNewSession(data);
        if(data.autoAnswer) //自动应答
        {
            console.info('坐席延迟2秒自动应答，防止无振铃声就接起！');
            setTimeout(top.softphone.answerBtnClick(), 2000);
        }
        top.softphone.insertCallHistory(top.softphone.sessionMap[sessionId]);//插入呼叫历史
    }
    else
    {
        console.info("user.Delivered call: 其他");
        
    }
});

/**
 * 接通电话
 * @param e
 * @returns
 */
event.on('user.Established', function (e)
{
    top.softphone.agentStatusTimeUpdate("通话中");
    top.softphone.answerBtnStatusUpdate(false);
    top.softphone.hangupBtnStatusUpdate(true);
    top.softphone.holdBtnStatusUpdate(true);
    console.info("user.Established", e);    
    let call = station.calls.get(e.callId);
    if (!call) return;
    console.info("user.Established call", call);
    //直接呼叫分机接通
    if (( typeof e.userData === 'undefined' || 
          e.userData === null || 
          typeof e.userData.map === 'undefined' || 
          e.userData.map === null || 
          typeof e.userData.map.uui === 'undefined' || 
          e.userData.map.uui === null
        ) &&
        e.answeringDevice === station.deviceId && 
        ( e.calledDevice === station.deviceId || 
          e.calledDevice === station.agent.agentId
        )
       )
    {
        console.info("user.Established call: 直接呼叫分机接通");
    }
    //直接呼叫技能组呼入接通
    else if ((typeof e.userData === 'undefined' || 
              e.userData === null || 
              typeof e.userData.map === 'undefined' || 
              e.userData.map === null || 
              typeof e.userData.map.uui === 'undefined' || 
              e.userData.map.uui === null 
             ) &&
             e.answeringDevice === station.deviceId && 
             e.calledDevice !== station.deviceId && 
             e.calledDevice !== station.agent.agentId && 
             typeof e.split !== 'undefined' && 
             e.split !== null && 
             e.split !== ""
            )
    {
        console.info("user.Established call: 直接呼叫技能组呼入接通");
        let contactId = e.contactId;
        let sessionId = top.softphone.ucidMap[contactId];
        let ucid = top.softphone.sessionMap[sessionId].ucid;
        top.softphone.sessionMap[sessionId]['isconnected'] = true;
        top.softphone.currentUcid = ucid;
        top.softphone.currentContactId = contactId;
        //激活会话
        top.softphone.activeSession(sessionId);
        top.softphone.updateCallHistory("answer", top.softphone.sessionMap[sessionId]);//更新通话历史
    }
    //外呼首次应答
    else if ((typeof e.userData === 'undefined' || 
              e.userData === null || 
              typeof e.userData.map === 'undefined' || 
              e.userData.map === null || 
              typeof e.userData.map.uui === 'undefined' || 
              e.userData.map.uui === null 
             ) &&
             e.answeringDevice !== station.deviceId && 
             e.answeringDevice !== station.agent.agentId && 
             e.callingDevice === station.deviceId && 
             e.calledDevice !== station.deviceId && 
             e.calledDevice !== station.agent.agentId && 
             (typeof e.split === 'undefined' || 
              e.split === null || 
              e.split === ""
             )
            )
    {
        console.info("user.Established call: 外呼首次接通事件");
        let contactId = e.contactId;
        let sessionId = top.softphone.ucidMap[contactId];
        if(typeof sessionId === 'undefined' || sessionId === null || sessionId === "")
        {
            console.info("user.Established conferenceTransferIVR: 会议转接IVR接通事件");
            top.softphone.completeConferenceBtnClick();
            return;
        }
        let ucid = top.softphone.sessionMap[sessionId].ucid;
        top.softphone.sessionMap[sessionId]['isconnected'] = true;
        top.softphone.currentUcid = ucid;
        top.softphone.currentContactId = contactId;
        //激活会话
        top.softphone.activeSession(sessionId);
        top.softphone.updateCallHistory("answer", top.softphone.sessionMap[sessionId]);//更新通话历史 
    }
    //自助语音IVR首次呼入接通
    else if (typeof e.userData !== 'undefined' && 
             e.userData !== null && 
             typeof e.userData.map !== 'undefined' && 
             e.userData.map !== null && 
             typeof e.userData.map.uui !== 'undefined' && 
             e.userData.map.uui !== null &&
             (typeof e.userData.map.type === 'undefined' || 
              e.userData.map.type === null || 
              e.userData.map.type === ""
             ) && 
             e.answeringDevice === station.deviceId && 
             e.calledDevice !== station.agent.agentId
            )
    {
        console.info("user.Established call: 自助语音IVR首次呼入接通");
        let ucid = e.userData.map.uui;
        let sessionId = top.softphone.ucidMap[ucid];
        let contactId = top.softphone.sessionMap[sessionId].contactId;
        top.softphone.sessionMap[sessionId]['isconnected'] = true;
        top.softphone.currentUcid = ucid;
        top.softphone.currentContactId = contactId;
        //激活会话
        top.softphone.activeSession(sessionId);
        top.softphone.updateCallHistory("answer", top.softphone.sessionMap[sessionId]);//更新通话历史 
    }
    //自助语音IVR转回人工接通
    else if (typeof e.userData !== 'undefined' && 
             e.userData !== null && 
             typeof e.userData.map !== 'undefined' && 
             e.userData.map !== null && 
             typeof e.userData.map.uui !== 'undefined' && 
             e.userData.map.uui !== null &&
             (typeof e.userData.map.type === 'undefined' || 
              e.userData.map.type === null || 
              e.userData.map.type === ""
             ) && 
             e.answeringDevice === station.deviceId && 
             e.calledDevice === station.agent.agentId
            )
    {
        console.info("user.Established call: 自助语音转回人工接通");
        let ucid = e.userData.map.uui;
        let sessionId = top.softphone.ucidMap[ucid];
        let contactId = top.softphone.sessionMap[sessionId].contactId;
        top.softphone.sessionMap[sessionId]['isconnected'] = true;
        top.softphone.currentUcid = ucid;
        top.softphone.currentContactId = contactId;
        //激活会话
        top.softphone.activeSession(sessionId);
        top.softphone.updateCallHistory("ivranswer", top.softphone.sessionMap[sessionId]);//更新通话历史
    }
    //其他坐席转接过来首次接通
    else if (typeof e.userData !== 'undefined' && 
             e.userData !== null && 
             typeof e.userData.map !== 'undefined' && 
             e.userData.map !== null && 
             typeof e.userData.map.uui !== 'undefined' && 
             e.userData.map.uui !== null &&
             typeof e.userData.map.type !== 'undefined' && 
             e.userData.map.type !== null && 
             e.userData.map.type === "t" && 
             e.answeringDevice === station.deviceId && 
             e.calledDevice === station.agent.agentId
            )
    {
        console.info("user.Established call: 其他坐席转接过来首次接通");
        let ucid = e.userData.map.uui;
        let sessionId = top.softphone.ucidMap[ucid];
        let contactId = top.softphone.sessionMap[sessionId].contactId;
        top.softphone.sessionMap[sessionId]['isconnected'] = true;
        top.softphone.currentUcid = ucid;
        top.softphone.currentContactId = contactId;
        //激活会话
        top.softphone.activeSession(sessionId);
        top.softphone.updateCallHistory("answer", top.softphone.sessionMap[sessionId]);//更新通话历史
    }
    //其他坐席通过技能组转接过来首次接通
    else if (typeof e.userData !== 'undefined' && 
             e.userData !== null && 
             typeof e.userData.map !== 'undefined' && 
             e.userData.map !== null && 
             typeof e.userData.map.uui !== 'undefined' && 
             e.userData.map.uui !== null &&
             typeof e.userData.map.type !== 'undefined' && 
             e.userData.map.type !== null && 
             e.userData.map.type === "g" && 
             e.answeringDevice === station.deviceId && 
             e.calledDevice !== station.agent.agentId
            )
    {
        console.info("user.Established call: 其他坐席通过技能组转接过来首次接通");
        let ucid = e.userData.map.uui;
        let sessionId = top.softphone.ucidMap[ucid];
        let contactId = top.softphone.sessionMap[sessionId].contactId;
        top.softphone.sessionMap[sessionId]['isconnected'] = true;
        top.softphone.currentUcid = ucid;
        top.softphone.currentContactId = contactId;
        //激活会话
        top.softphone.activeSession(sessionId);
        top.softphone.updateCallHistory("answer", top.softphone.sessionMap[sessionId]);//更新通话历史
    }
    //其他坐席邀请会议首次接通
    else if (typeof e.userData !== 'undefined' && 
             e.userData !== null && 
             typeof e.userData.map !== 'undefined' && 
             e.userData.map !== null && 
             typeof e.userData.map.uui !== 'undefined' && 
             e.userData.map.uui !== null &&
             typeof e.userData.map.type !== 'undefined' && 
             e.userData.map.type !== null && 
             e.userData.map.type === "c" && 
             e.answeringDevice === station.deviceId && 
             e.calledDevice === station.agent.agentId
            )
    {
        console.info("user.Established call: 其他坐席邀请会议首次接通");
        let ucid = e.userData.map.uui;
        let sessionId = top.softphone.ucidMap[ucid];
        let contactId = top.softphone.sessionMap[sessionId].contactId;
        top.softphone.sessionMap[sessionId]['isconnected'] = true;
        top.softphone.currentUcid = ucid;
        top.softphone.currentContactId = contactId;
        //激活会话
        top.softphone.activeSession(sessionId);
        top.softphone.updateCallHistory("answer", top.softphone.sessionMap[sessionId]);//更新通话历史
    }
    else
    {
        console.info("user.Delivered call: 其他");
        
    }
});
/**
 * @author lqzheng
 * @description 电话挂断事件
 * @date 2020/11/30
 **/
event.on('user.ConnectionCleared', function (e)
{
    console.info("user.ConnectionCleared station:", station);
    console.info("user.ConnectionCleared", e);
    let call = station.calls.get(e.callId);
    console.info("user.ConnectionCleared call", call);
    let contactId = e.contactId;
    let sessionId = top.softphone.ucidMap[contactId];
    if(call && sessionId && e.releasingDevice !== e.srcDeviceId && e.releasingDevice === e.deviceId) //客户挂机事件
    {
        let whoDropCall = top.softphone.sessionMap[sessionId]['whoDropCall'];
        if(whoDropCall === null || whoDropCall === "")
        {
            top.softphone.sessionMap[sessionId]['whoDropCall'] = "cust"; //挂机端-客户
        }
        top.softphone.sessionMap[sessionId]['isHangup'] = true;
    }
    if(!call && sessionId && e.releasingDevice === e.srcDeviceId) //坐席挂机事件
    {
        let ucid = top.softphone.sessionMap[sessionId].ucid;
        top.softphone.sessionMap[sessionId]['isHangup'] = true;
        if(!top.softphone.sessionMap[sessionId]['isconnected'])//未接起挂断
        {
            top.softphone.sessionMap[sessionId]['whoDropCall'] = "notconnected";
        }
        let whoDropCall = top.softphone.sessionMap[sessionId]['whoDropCall'];
        if(whoDropCall === null || whoDropCall === "")
        {
            top.softphone.sessionMap[sessionId]['whoDropCall'] = "agent"; //挂机端-坐席
        }
        top.softphone.holdBtnLabelUpdate("保持");
        top.softphone.holdBtnStatusUpdate(false);
        top.softphone.currentUcid = ucid;
        top.softphone.currentContactId = contactId;
        top.softphone.answerBtnStatusUpdate(false);
        //激活会话
        top.softphone.activeSession(sessionId);
        afterHangup(sessionId);//挂机后操作
    }
    if(sessionId)
    {
        console.info("user.ConnectionCleared sessionMap", top.softphone.sessionMap[sessionId]); 
    }
});

var talkState = false;
// 监听电话改变事件
event.on('user.StationStateChange', function (e) {
    console.info("user.StationStateChange station:", station);
    console.info("user.StationStateChange:", e);
    if(e && typeof e.name !== 'undefined' && e.name !== null && e.name !== "")
    {
        switch (e.name)
        {
            case "held"://保持
                widget.info('保持');
                top.softphone.holdBtnLabelUpdate("恢复");
                top.softphone.holdBtnStatusUpdate(true);
                break;
            case "retrieved"://恢复
                widget.info("恢复");
                top.softphone.holdBtnLabelUpdate("保持");
                top.softphone.holdBtnStatusUpdate(true);
                break;
            case "transferred"://电话转移后
                widget.info("恢复");
                top.softphone.holdBtnLabelUpdate("保持");
                top.softphone.holdBtnStatusUpdate(false);
                break;
            default:
                break;
        }
    }
    if (e.source !== station.deviceId) return;
    if (talkState && station.calls.size() === 0) {
        talkState = false;
    } else if (!talkState && station.calls.size() > 0) {
        talkState = true;
    }
});
//会议完成
event.on('user.Conferenced', function (e) {
   console.info("user.Conferenced", e);
   let contactId = e.contactId;
   let sessionId = top.softphone.ucidMap[contactId];
   if(top.softphone.sessionMap[sessionId].isTransferIvr)
   {
       top.softphone.holdBtnClick();
   }
});
//转接完成
event.on('user.Transferred', function (e)
{
    console.info("user.Transferred", e);
});

//代接事件
event.on('user.Diverted', function (e) {
    top.softphone.answerBtnStatusUpdate(false);
    console.info("user.Diverted station:", station);
    console.info("user.Diverted", e);
    console.info("user.Diverted dropHandle: 代接进行挂机处理");
    let contactId = e.contactId;
    let sessionId = top.softphone.ucidMap[contactId];
    if(!top.softphone.sessionMap[sessionId]['isconnected'])//未接起代接
    {
        top.softphone.sessionMap[sessionId]['whoDropCall'] = "diverted";
    }
    else //IVR转回代接
    {
        top.softphone.sessionMap[sessionId]['whoDropCall'] = "IVRdiverted";
    }
    afterHangup(sessionId);//挂机后操作
});

//语音坐席就绪事件
event.on('user.AgentReady', function (e) {
    console.info("user.AgentReady", e);
});

function sleep(n)
{
    let start=new Date().getTime();
    while(true){
        if(new Date().getTime()-start> n){
            break;
        }
    }   
}